package com.example.demo.services.impl;

import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.dao.UserMapper;
import com.example.demo.exception.ApplicationException;
import com.example.demo.model.User;
import com.example.demo.services.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        if (user == null) {
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        // 查询当前⽤户是否存在
        User existUser = userMapper.selectByUserName(user.getUsername());
        if (existUser != null) {
            // 记录⽇志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username = "
                    + user.getUsername());
            // 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        // 除了注册时传⼊的有效值，其他全部使⽤默认
        if (user.getGender() == null) {
            // 性别赋默认值
            user.setGender((byte) 2);
        }
        // 填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            // 记录⽇志
            log.info(ResultCode.FAILED_CREATE.toString() + "username = " +
                    user.getUsername());
            // 抛出异常
            throw new
                    ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 记录⽇志
        log.info("新增⽤⼾成功：username = " + user.getUsername());
    }

}
